//引入包资源
const express = require('express')
const EmployeeModel = require('../models/employee')
//定义路由
const router = express.Router()

router.get('/:_id?', (req, res, next) => {
    const {_id} = req.params
    //通过id查询单个数据
    if (_id) {
        EmployeeModel.findById(_id).then(data => {
            res.json({
                code: 200,
                data
            })
        })
    } 
    //通过传入页数和一页显示的数据量分页查询数据
    else {
        let {page = 1, pageSize = 10} = req.query
        page = Number(page)
        pageSize = Number(pageSize)
        EmployeeModel.find().limit(pageSize).skip((page - 1) * pageSize).then(data => {
            res.json({
                code: 200,
                data
            })
        })
    }
})
//员工信息添加
router.post('/', (req, res, next) => {
    const {name, sex, birthday, cid, phone} = req.body
    const employee = new EmployeeModel({name, sex, birthday, cid, phone, joinTime: Date.now()});
    employee.save().then(data => {
        res.json({
            code: 200,
            data: {
                status: 200,
                message: '添加成功',
                employee: data
            }
        })
    });
})
router.put('/:_id', (req, res, next) => {
    const {_id} = req.params
    const {name, sex, birthday, cid, phone} = req.body
    EmployeeModel
        .updateOne({_id}, {name, sex, birthday, cid, phone})
        .then(data => {
            if (data.modifiedCount !== 0) {
                res.json({
                    code: 200,
                    data: {
                        status: 200,
                        message: "修改成功！"
                    }
                })
            }
            res.json({
                code: 200,
                data: {
                    status: 400,
                    message: "未修改任何数据！"
                }
            })
        })

    //res.send('put请求')
})
router.delete('/:_id', (req, res, next) => {
    const {_id } = req.params
    EmployeeModel.remove({_id}).then(data => {
        if (data.deletedCount !== 0) {
            res.json({
                code: 200,
                data: {
                    status: 200,
                    message: "删除成功！"
                }
            })
        }
        res.json({
            code: 200,
            data: {
                status: 400,
                message: "未删除任何数据！"
            }
        })
    })
    //res.send('delete请求')
})

module.exports = router